#!/usr/bin/python3
# -*- coding: utf-8 -*-
import hmac
import hashlib
import urllib
import urllib.parse
import json
import time
import base64
import requests
import datetime


class dingtalkMessage(object):
    def __init__(self):
        self.times = None
        self.sign = None
        self.response = None

    def weather(self):
        url = 'http://t.weather.sojson.com/api/weather/city/101280601'
        r = requests.get(url)
        response_data = r.json()
        result = json.dumps(response_data, sort_keys=True, indent=2, ensure_ascii=False)
        r = json.loads(result)
        self.response = r['cityInfo']['city'] + '\n' + r['time'] + '\n' + r['data']['forecast'][0][
            'type'] + '\n' + r['data']['forecast'][0]['high'] + '\n' + r['data']['forecast'][0][
                            'low'] + '\n' + r['data']['forecast'][0]['notice']

    def signature(self):
        self.times = int(round(time.time() * 1000))
        # 调试 secret = 'SEC12808f1d15e1e4722ab587c65ff28edaf00962701d3116cc698f1add5e820208'
        # 测试 secret = 'SEC3a0275898d1f366619e0f953e374a1226259deb788c71f3771fadf38c619df6f'
        secret = 'SEC3a0275898d1f366619e0f953e374a1226259deb788c71f3771fadf38c619df6f'
        secret_enc = str(secret).encode('utf-8')
        string_to_sign = '{}\n{}'.format(self.times, secret)
        string_to_sign_enc = str(string_to_sign).encode('utf-8')
        hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
        self.sign = urllib.parse.quote(base64.b64encode(hmac_code))

    def text(self):
        # 调试 https://oapi.dingtalk.com/robot/send?access_token=6d9595d480610e650bd7462de5525249c44ffb0c7f47f66346ed44f8ed89bc20
        # 测试 https://oapi.dingtalk.com/robot/send?access_token=a48ee18f5c005ee2c348d4a76a50223ebaa1fd761929533ae972735b10062f40
        url = 'https://oapi.dingtalk.com/robot/send?access_token=a48ee18f5c005ee2c348d4a76a50223ebaa1fd761929533ae972735b10062f40' + '&timestamp=' + str(
            self.times) + '&sign=' + self.sign
        data_text = {
            "msgtype": "text",
            "text": {
                "content": self.response
            },
            "at": {
                "atMobiles": [
                    "17620533205",
                    "189xxxx8325"
                ],
                "isAtAll": False
            }
        }
        headers = {
            'Content-Type': 'application/json'
        }
        r1 = requests.post(url, data=json.dumps(data_text), headers=headers)
        # r2 = r1.json()
        # print(r2)
        print("推送成功")

    def markDown(self):
        pic = dt.uploadJpg()
        url = 'https://oapi.dingtalk.com/robot/send?access_token=a48ee18f5c005ee2c348d4a76a50223ebaa1fd761929533ae972735b10062f40' + '&timestamp=' + str(
            self.times) + '&sign=' + self.sign
        data_markdown = {
            "msgtype": "markdown",
            "markdown": {
                "title": "python培训",
                "text": f"人生苦短，我爱python!![avatar]({pic})"
            },
            "at": {
                "atMobiles": [
                    "17620533205",
                    "11111111111"
                ],
                "isAtAll": True
            }
        }
        headers = {
            'Content-Type': 'application/json'
        }
        r1 = requests.post(url, data=json.dumps(data_markdown), headers=headers)
        # r2 = r1.json()
        # print(r2)
        print("推送成功")

    def dataLink(self):
        pic = dt.uploadJpg()
        url = 'https://oapi.dingtalk.com/robot/send?access_token=a48ee18f5c005ee2c348d4a76a50223ebaa1fd761929533ae972735b10062f40' + '&timestamp=' + str(
            self.times) + '&sign=' + self.sign
        data_link = {
            "msgtype": "link",
            "link": {
                "text": "人生苦短，我爱python!",
                "title": "python培训",
                "picUrl": pic,
                "messageUrl": "https://down1.cmfspay.com/static/python/_book/"
            }
        }
        headers = {
            'Content-Type': 'application/json'
        }
        r1 = requests.post(url, data=json.dumps(data_link), headers=headers)
        # r2 = r1.json()
        # print(r2)
        print("推送成功")

    @staticmethod
    def uploadJpg():
        url = "https://sm.ms/api/v2/upload?inajax=1"
        apiToken = "0Gff5VNOQv9XcCVZjfOt2kllsshVV7OH"
        headers = {
            "content-type": "multipart/form-data ",
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 "
                          "Safari/537.36",
            "Authorization": apiToken
        }
        files = {
            'smfile': open(r"/wangzhijing/screenshot.jpg", "rb"),  # => 用name指定文件
            'Content-Disposition': 'form-data',
            'Content-Type': 'image/jpeg',
            'filename': 'screenshot.jpg'
        }
        r1 = requests.post(url, files=files)  # => 注意这里，参数名是 files
        r2 = r1.json()
        # print(json.dumps(r2, ensure_ascii=False, indent=4))
        # picUrl = r2['data']['url']
        try:
            picUrl = r2['data']['url']
        except:
            picUrl = r2['images']
            return picUrl
        else:
            return picUrl


while True:
    dt = dingtalkMessage()
    today = datetime.datetime.now()
    weekday = today.isoweekday()
    t1 = str(time.strftime("%H:%M:%S"))
    t2 = str(time.strftime("08:00:00"))
    t3 = str(time.strftime("20:00:00"))
    t4 = str(time.strftime("17:00:00"))
    print(today)
    time.sleep(1)
    if weekday == 3 or weekday == 4:
        if t1 == t4:
            dt.weather()
            dt.signature()
            dt.dataLink()
            dt.markDown()
        elif t1 == t2 or t1 == t3:
            dt.weather()
            dt.signature()
            dt.text()
        else:
            continue
    else:
        if t1 == t2 or t1 == t3:
            dt.weather()
            dt.signature()
            dt.text()
        else:
            continue
